home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1993 July / InfoMagic USENET CD-ROM July 1993.ISO / sources / unix / volume22 / gawk2.11 / part05 < prev    next >
Encoding:
Internet Message Format  |  1990-06-07  |  54.0 KB

  1. Subject:  v22i091:  GNU AWK, version 2.11, Part05/16
  2. Newsgroups: comp.sources.unix
  3. Approved: rsalz@uunet.UU.NET
  4. X-Checksum-Snefru: 33f94e15 6a8854a7 37c034b6 598cf985
  5.  
  6. Submitted-by: "Arnold D. Robbins" <arnold@unix.cc.emory.edu>
  7. Posting-number: Volume 22, Issue 91
  8. Archive-name: gawk2.11/part05
  9.  
  10. #! /bin/sh
  11. # This is a shell archive.  Remove anything before this line, then feed it
  12. # into a shell via "sh file" or similar.  To overwrite existing files,
  13. # type "sh file -c".
  14. # The tool that generated this appeared in the comp.sources.unix newsgroup;
  15. # send mail to comp-sources-unix@uunet.uu.net if you want that tool.
  16. # Contents:  ./gawk.texinfo.02 ./regex.c.02
  17. # Wrapped by rsalz@litchi.bbn.com on Wed Jun  6 12:24:49 1990
  18. PATH=/bin:/usr/bin:/usr/ucb ; export PATH
  19. echo If this archive is complete, you will see the following message:
  20. echo '          "shar: End of archive 5 (of 16)."'
  21. if test -f './gawk.texinfo.02' -a "${1}" != "-c" ; then 
  22.   echo shar: Will not clobber existing file \"'./gawk.texinfo.02'\"
  23. else
  24.   echo shar: Extracting \"'./gawk.texinfo.02'\" \(49665 characters\)
  25.   sed "s/^X//" >'./gawk.texinfo.02' <<'END_OF_FILE'
  26. XThe input is read in units called @dfn{records}, and processed by the
  27. Xrules one record at a time.  By default, each record is one line.  Each
  28. Xrecord read is split automatically into @dfn{fields}, to make it more
  29. Xconvenient for a rule to work on parts of the record under
  30. Xconsideration.
  31. X
  32. XOn rare occasions you will need to use the @code{getline} command,
  33. Xwhich can do explicit input from any number of files (@pxref{Getline}).
  34. X
  35. X@menu
  36. X* Records::             Controlling how data is split into records.
  37. X* Fields::              An introduction to fields.
  38. X* Non-Constant Fields:: Non-constant Field Numbers.
  39. X* Changing Fields::     Changing the Contents of a Field.
  40. X* Field Separators::    The field separator and how to change it.
  41. X* Multiple Line::       Reading multi-line records.
  42. X
  43. X* Getline::             Reading files under explicit program control
  44. X                        using the @code{getline} function.
  45. X
  46. X* Close Input::         Closing an input file (so you can read from
  47. X                        the beginning once more).
  48. X@end menu
  49. X
  50. X@node Records, Fields, Reading Files, Reading Files
  51. X@section How Input is Split into Records
  52. X
  53. X@cindex record separator
  54. XThe @code{awk} language divides its input into records and fields.
  55. XRecords are separated by a character called the @dfn{record separator}.
  56. XBy default, the record separator is the newline character.  Therefore,
  57. Xnormally, a record is a line of text.@refill
  58. X
  59. X@c @cindex changing the record separator
  60. X@vindex RS
  61. XSometimes you may want to use a different character to separate your
  62. Xrecords.  You can use different characters by changing the built-in
  63. Xvariable @code{RS}.  
  64. X
  65. XThe value of @code{RS} is a string that says how to separate records;
  66. Xthe default value is @code{"\n"}, the string of just a newline
  67. Xcharacter.  This is why records are, by default, single lines.
  68. X
  69. X@code{RS} can have any string as its value, but only the first character
  70. Xof the string is used as the record separator.  The other characters are
  71. Xignored.  @code{RS} is exceptional in this regard; @code{awk} uses the
  72. Xfull value of all its other built-in variables.@refill
  73. X
  74. X@ignore
  75. XSomeday this should be true!
  76. X
  77. XThe value of @code{RS} is not limited to a one-character string.  It can
  78. Xbe any regular expression (@pxref{Regexp}).  In general, each record
  79. Xends at the next string that matches the regular expression; the next
  80. Xrecord starts at the end of the matching string.  This general rule is
  81. Xactually at work in the usual case, where @code{RS} contains just a
  82. Xnewline: a record ends at the beginning of the next matching string (the
  83. Xnext newline in the input) and the following record starts just after
  84. Xthe end of this string (at the first character of the following line).
  85. XThe newline, since it matches @code{RS}, is not part of either record.
  86. X@end ignore
  87. X
  88. XYou can change the value of @code{RS} in the @code{awk} program with the
  89. Xassignment operator, @samp{=} (@pxref{Assignment Ops}).  The new
  90. Xrecord-separator character should be enclosed in quotation marks to make
  91. Xa string constant.  Often the right time to do this is at the beginning
  92. Xof execution, before any input has been processed, so that the very
  93. Xfirst record will be read with the proper separator.  To do this, use
  94. Xthe special @code{BEGIN} pattern (@pxref{BEGIN/END}).  For
  95. Xexample:@refill
  96. X
  97. X@example
  98. Xawk 'BEGIN @{ RS = "/" @} ; @{ print $0 @}' BBS-list
  99. X@end example
  100. X
  101. X@noindent
  102. Xchanges the value of @code{RS} to @code{"/"}, before reading any input.
  103. XThis is a string whose first character is a slash; as a result, records
  104. Xare separated by slashes.  Then the input file is read, and the second
  105. Xrule in the @code{awk} program (the action with no pattern) prints each
  106. Xrecord.  Since each @code{print} statement adds a newline at the end of
  107. Xits output, the effect of this @code{awk} program is to copy the input
  108. Xwith each slash changed to a newline.
  109. X
  110. XAnother way to change the record separator is on the command line,
  111. Xusing the variable-assignment feature (@pxref{Command Line}).
  112. X
  113. X@example
  114. Xawk '@dots{}' RS="/" @var{source-file}
  115. X@end example
  116. X
  117. X@noindent
  118. XThis sets @code{RS} to @samp{/} before processing @var{source-file}.
  119. X
  120. XThe empty string (a string of no characters) has a special meaning
  121. Xas the value of @code{RS}: it means that records are separated only
  122. Xby blank lines.  @xref{Multiple Line}, for more details.
  123. X
  124. X@cindex number of records, @code{NR} or @code{FNR}
  125. X@vindex NR
  126. X@vindex FNR
  127. XThe @code{awk} utility keeps track of the number of records that have
  128. Xbeen read so far from the current input file.  This value is stored in a
  129. Xbuilt-in variable called @code{FNR}.  It is reset to zero when a new
  130. Xfile is started.  Another built-in variable, @code{NR}, is the total
  131. Xnumber of input records read so far from all files.  It starts at zero
  132. Xbut is never automatically reset to zero.
  133. X
  134. XIf you change the value of @code{RS} in the middle of an @code{awk} run,
  135. Xthe new value is used to delimit subsequent records, but the record
  136. Xcurrently being processed (and records already finished) are not
  137. Xaffected.
  138. X
  139. X@node Fields, Non-Constant Fields, Records, Reading Files
  140. X@section Examining Fields
  141. X
  142. X@cindex examining fields
  143. X@cindex fields
  144. X@cindex accessing fields
  145. XWhen @code{awk} reads an input record, the record is
  146. Xautomatically separated or @dfn{parsed} by the interpreter into pieces
  147. Xcalled @dfn{fields}.  By default, fields are separated by whitespace,
  148. Xlike words in a line.
  149. XWhitespace in @code{awk} means any string of one or more spaces and/or
  150. Xtabs; other characters such as newline, formfeed, and so on, that are
  151. Xconsidered whitespace by other languages are @emph{not} considered
  152. Xwhitespace by @code{awk}.
  153. X
  154. XThe purpose of fields is to make it more convenient for you to refer to
  155. Xthese pieces of the record.  You don't have to use them---you can
  156. Xoperate on the whole record if you wish---but fields are what make
  157. Xsimple @code{awk} programs so powerful.
  158. X
  159. X@cindex @code{$} (field operator)
  160. X@cindex operators, @code{$}
  161. XTo refer to a field in an @code{awk} program, you use a dollar-sign,
  162. X@samp{$}, followed by the number of the field you want.  Thus, @code{$1}
  163. Xrefers to the first field, @code{$2} to the second, and so on.  For
  164. Xexample, suppose the following is a line of input:@refill
  165. X
  166. X@example
  167. XThis seems like a pretty nice example.
  168. X@end example
  169. X
  170. X@noindent
  171. XHere the first field, or @code{$1}, is @samp{This}; the second field, or
  172. X@code{$2}, is @samp{seems}; and so on.  Note that the last field,
  173. X@code{$7}, is @samp{example.}.  Because there is no space between the
  174. X@samp{e} and the @samp{.}, the period is considered part of the seventh
  175. Xfield.@refill
  176. X
  177. XNo matter how many fields there are, the last field in a record can be
  178. Xrepresented by @code{$NF}.  So, in the example above, @code{$NF} would
  179. Xbe the same as @code{$7}, which is @samp{example.}.  Why this works is
  180. Xexplained below (@pxref{Non-Constant Fields}).  If you try to refer to a
  181. Xfield beyond the last one, such as @code{$8} when the record has only 7
  182. Xfields, you get the empty string.
  183. X
  184. X@vindex NF
  185. X@cindex number of fields, @code{NF}
  186. XPlain @code{NF}, with no @samp{$}, is a built-in variable whose value
  187. Xis the number of fields in the current record.
  188. X
  189. X@code{$0}, which looks like an attempt to refer to the zeroth field, is
  190. Xa special case: it represents the whole input record.  This is what you
  191. Xwould use when you aren't interested in fields.
  192. X
  193. XHere are some more examples:
  194. X
  195. X@example
  196. Xawk '$1 ~ /foo/ @{ print $0 @}' BBS-list
  197. X@end example
  198. X
  199. X@noindent
  200. XThis example prints each record in the file @file{BBS-list} whose first
  201. Xfield contains the string @samp{foo}.  The operator @samp{~} is called a
  202. X@dfn{matching operator} (@pxref{Comparison Ops}); it tests whether a
  203. Xstring (here, the field @code{$1}) contains a match for a given regular
  204. Xexpression.@refill
  205. X
  206. XBy contrast, the following example:
  207. X
  208. X@example
  209. Xawk '/foo/ @{ print $1, $NF @}' BBS-list
  210. X@end example
  211. X
  212. X@noindent
  213. Xlooks for @samp{foo} in @emph{the entire record} and prints the first
  214. Xfield and the last field for each input record containing a
  215. Xmatch.@refill
  216. X
  217. X@node Non-Constant Fields, Changing Fields, Fields, Reading Files
  218. X@section Non-constant Field Numbers
  219. X
  220. XThe number of a field does not need to be a constant.  Any expression in
  221. Xthe @code{awk} language can be used after a @samp{$} to refer to a
  222. Xfield.  The value of the expression specifies the field number.  If the
  223. Xvalue is a string, rather than a number, it is converted to a number.
  224. XConsider this example:@refill
  225. X
  226. X@example
  227. Xawk '@{ print $NR @}'
  228. X@end example
  229. X
  230. X@noindent
  231. XRecall that @code{NR} is the number of records read so far: 1 in the
  232. Xfirst record, 2 in the second, etc.  So this example prints the first
  233. Xfield of the first record, the second field of the second record, and so
  234. Xon.  For the twentieth record, field number 20 is printed; most likely,
  235. Xthe record has fewer than 20 fields, so this prints a blank line.
  236. X
  237. XHere is another example of using expressions as field numbers:
  238. X
  239. X@example
  240. Xawk '@{ print $(2*2) @}' BBS-list
  241. X@end example
  242. X
  243. XThe @code{awk} language must evaluate the expression @code{(2*2)} and use
  244. Xits value as the number of the field to print.  The @samp{*} sign
  245. Xrepresents multiplication, so the expression @code{2*2} evaluates to 4.
  246. XThe parentheses are used so that the multiplication is done before the
  247. X@samp{$} operation; they are necessary whenever there is a binary
  248. Xoperator in the field-number expression.  This example, then, prints the
  249. Xhours of operation (the fourth field) for every line of the file
  250. X@file{BBS-list}.@refill
  251. X
  252. XIf the field number you compute is zero, you get the entire record.
  253. XThus, @code{$(2-2)} has the same value as @code{$0}.  Negative field
  254. Xnumbers are not allowed.
  255. X
  256. XThe number of fields in the current record is stored in the built-in
  257. Xvariable @code{NF} (@pxref{Built-in Variables}).  The expression
  258. X@code{$NF} is not a special feature: it is the direct consequence of
  259. Xevaluating @code{NF} and using its value as a field number.
  260. X
  261. X@node Changing Fields, Field Separators, Non-Constant Fields, Reading Files
  262. X@section Changing the Contents of a Field
  263. X
  264. X@cindex field, changing contents of
  265. X@cindex changing contents of a field
  266. X@cindex assignment to fields
  267. XYou can change the contents of a field as seen by @code{awk} within an
  268. X@code{awk} program; this changes what @code{awk} perceives as the
  269. Xcurrent input record.  (The actual input is untouched: @code{awk} never
  270. Xmodifies the input file.)
  271. X
  272. XLook at this example:
  273. X
  274. X@example
  275. Xawk '@{ $3 = $2 - 10; print $2, $3 @}' inventory-shipped
  276. X@end example
  277. X
  278. X@noindent
  279. XThe @samp{-} sign represents subtraction, so this program reassigns
  280. Xfield three, @code{$3}, to be the value of field two minus ten,
  281. X@code{$2 - 10}.  (@xref{Arithmetic Ops}.)  Then field two, and the
  282. Xnew value for field three, are printed.  
  283. X
  284. XIn order for this to work, the text in field @code{$2} must make sense
  285. Xas a number; the string of characters must be converted to a number in
  286. Xorder for the computer to do arithmetic on it.  The number resulting
  287. Xfrom the subtraction is converted back to a string of characters which
  288. Xthen becomes field three.  @xref{Conversion}.
  289. X
  290. XWhen you change the value of a field (as perceived by @code{awk}), the
  291. Xtext of the input record is recalculated to contain the new field where
  292. Xthe old one was.  Therefore, @code{$0} changes to reflect the altered
  293. Xfield.  Thus,
  294. X
  295. X@example
  296. Xawk '@{ $2 = $2 - 10; print $0 @}' inventory-shipped
  297. X@end example
  298. X
  299. X@noindent
  300. Xprints a copy of the input file, with 10 subtracted from the second
  301. Xfield of each line.
  302. X
  303. XYou can also assign contents to fields that are out of range.  For
  304. Xexample:
  305. X
  306. X@example
  307. Xawk '@{ $6 = ($5 + $4 + $3 + $2) ; print $6 @}' inventory-shipped
  308. X@end example
  309. X
  310. X@noindent
  311. XWe've just created @code{$6}, whose value is the sum of fields
  312. X@code{$2}, @code{$3}, @code{$4}, and @code{$5}.  The @samp{+} sign
  313. Xrepresents addition.  For the file @file{inventory-shipped}, @code{$6}
  314. Xrepresents the total number of parcels shipped for a particular month.
  315. X
  316. XCreating a new field changes the internal @code{awk} copy of the current
  317. Xinput record---the value of @code{$0}.  Thus, if you do @samp{print $0}
  318. Xafter adding a field, the record printed includes the new field, with
  319. Xthe appropriate number of field separators between it and the previously
  320. Xexisting fields.
  321. X
  322. XThis recomputation affects and is affected by several features not yet
  323. Xdiscussed, in particular, the @dfn{output field separator}, @code{OFS},
  324. Xwhich is used to separate the fields (@pxref{Output Separators}), and
  325. X@code{NF} (the number of fields; @pxref{Fields}).  For example, the
  326. Xvalue of @code{NF} is set to the number of the highest field you
  327. Xcreate.@refill
  328. X
  329. XNote, however, that merely @emph{referencing} an out-of-range field
  330. Xdoes @emph{not} change the value of either @code{$0} or @code{NF}.
  331. XReferencing an out-of-range field merely produces a null string.  For
  332. Xexample:@refill
  333. X
  334. X@example
  335. Xif ($(NF+1) != "")
  336. X    print "can't happen"
  337. Xelse
  338. X    print "everything is normal"
  339. X@end example
  340. X
  341. X@noindent
  342. Xshould print @samp{everything is normal}, because @code{NF+1} is certain
  343. Xto be out of range.  (@xref{If Statement}, for more information about
  344. X@code{awk}'s @code{if-else} statements.)
  345. X
  346. X@node Field Separators, Multiple Line, Changing Fields, Reading Files
  347. X@section Specifying How Fields Are Separated
  348. X@vindex FS
  349. X@cindex fields, separating
  350. X@cindex field separator, @code{FS}
  351. X@cindex @samp{-F} option
  352. X
  353. XThe way @code{awk} splits an input record into fields is controlled by
  354. Xthe @dfn{field separator}, which is a single character or a regular
  355. Xexpression.  @code{awk} scans the input record for matches for the
  356. Xseparator; the fields themselves are the text between the matches.  For
  357. Xexample, if the field separator is @samp{oo}, then the following line:
  358. X
  359. X@example
  360. Xmoo goo gai pan
  361. X@end example
  362. X
  363. X@noindent
  364. Xwould be split into three fields: @samp{m}, @samp{@ g} and @samp{@ gai@ 
  365. Xpan}.
  366. X
  367. XThe field separator is represented by the built-in variable @code{FS}.
  368. XShell programmers take note!  @code{awk} does not use the name
  369. X@code{IFS} which is used by the shell.@refill
  370. X
  371. XYou can change the value of @code{FS} in the @code{awk} program with the
  372. Xassignment operator, @samp{=} (@pxref{Assignment Ops}).  Often the right
  373. Xtime to do this is at the beginning of execution, before any input has
  374. Xbeen processed, so that the very first record will be read with the
  375. Xproper separator.  To do this, use the special @code{BEGIN} pattern
  376. X(@pxref{BEGIN/END}).  For example, here we set the value of @code{FS} to
  377. Xthe string @code{","}:
  378. X
  379. X@example
  380. Xawk 'BEGIN @{ FS = "," @} ; @{ print $2 @}'
  381. X@end example
  382. X
  383. X@noindent
  384. XGiven the input line,
  385. X
  386. X@example
  387. XJohn Q. Smith, 29 Oak St., Walamazoo, MI 42139
  388. X@end example
  389. X
  390. X@noindent
  391. Xthis @code{awk} program extracts the string @samp{29 Oak St.}.
  392. X
  393. X@cindex field separator, choice of
  394. X@cindex regular expressions as field separators
  395. XSometimes your input data will contain separator characters that don't
  396. Xseparate fields the way you thought they would.  For instance, the
  397. Xperson's name in the example we've been using might have a title or
  398. Xsuffix attached, such as @samp{John Q. Smith, LXIX}.  From input
  399. Xcontaining such a name:
  400. X
  401. X@example
  402. XJohn Q. Smith, LXIX, 29 Oak St., Walamazoo, MI 42139
  403. X@end example
  404. X
  405. X@noindent
  406. Xthe previous sample program would extract @samp{LXIX}, instead of
  407. X@samp{29 Oak St.}.  If you were expecting the program to print the
  408. Xaddress, you would be surprised.  So choose your data layout and
  409. Xseparator characters carefully to prevent such problems.
  410. X
  411. XAs you know, by default, fields are separated by whitespace sequences
  412. X(spaces and tabs), not by single spaces: two spaces in a row do not
  413. Xdelimit an empty field.  The default value of the field separator is a
  414. Xstring @w{@code{" "}} containing a single space.  If this value were
  415. Xinterpreted in the usual way, each space character would separate
  416. Xfields, so two spaces in a row would make an empty field between them.
  417. XThe reason this does not happen is that a single space as the value of
  418. X@code{FS} is a special case: it is taken to specify the default manner
  419. Xof delimiting fields.
  420. X
  421. XIf @code{FS} is any other single character, such as @code{","}, then
  422. Xeach occurrence of that character separates two fields.  Two consecutive
  423. Xoccurrences delimit an empty field.  If the character occurs at the
  424. Xbeginning or the end of the line, that too delimits an empty field.  The
  425. Xspace character is the only single character which does not follow these
  426. Xrules.
  427. X
  428. XMore generally, the value of @code{FS} may be a string containing any
  429. Xregular expression.  Then each match in the record for the regular
  430. Xexpression separates fields.  For example, the assignment:@refill
  431. X
  432. X@example
  433. XFS = ", \t"
  434. X@end example
  435. X
  436. X@noindent
  437. Xmakes every area of an input line that consists of a comma followed by a
  438. Xspace and a tab, into a field separator.  (@samp{\t} stands for a
  439. Xtab.)@refill
  440. X
  441. XFor a less trivial example of a regular expression, suppose you want
  442. Xsingle spaces to separate fields the way single commas were used above.
  443. XYou can set @code{FS} to @w{@code{"[@ ]"}}.  This regular expression
  444. Xmatches a single space and nothing else.
  445. X
  446. X@cindex field separator, setting on command line
  447. X@cindex command line, setting @code{FS} on
  448. X@code{FS} can be set on the command line.  You use the @samp{-F} argument to
  449. Xdo so.  For example:
  450. X
  451. X@example
  452. Xawk -F, '@var{program}' @var{input-files}
  453. X@end example
  454. X
  455. X@noindent
  456. Xsets @code{FS} to be the @samp{,} character.  Notice that the argument uses
  457. Xa capital @samp{F}.  Contrast this with @samp{-f}, which specifies a file
  458. Xcontaining an @code{awk} program.  Case is significant in command options:
  459. Xthe @samp{-F} and @samp{-f} options have nothing to do with each other.
  460. XYou can use both options at the same time to set the @code{FS} argument
  461. X@emph{and} get an @code{awk} program from a file.
  462. X
  463. XAs a special case, in compatibility mode (@pxref{Command Line}), if the
  464. Xargument to @samp{-F} is @samp{t}, then @code{FS} is set to the tab
  465. Xcharacter.  (This is because if you type @samp{-F\t}, without the quotes,
  466. Xat the shell, the @samp{\} gets deleted, so @code{awk} figures that you
  467. Xreally want your fields to be separated with tabs, and not @samp{t}s.
  468. XUse @samp{FS="t"} on the command line if you really do want to separate
  469. Xyour fields with @samp{t}s.)
  470. X
  471. XFor example, let's use an @code{awk} program file called @file{baud.awk}
  472. Xthat contains the pattern @code{/300/}, and the action @samp{print $1}.
  473. XHere is the program:
  474. X
  475. X@example
  476. X/300/   @{ print $1 @}
  477. X@end example
  478. X
  479. XLet's also set @code{FS} to be the @samp{-} character, and run the
  480. Xprogram on the file @file{BBS-list}.  The following command prints a
  481. Xlist of the names of the bulletin boards that operate at 300 baud and
  482. Xthe first three digits of their phone numbers:@refill
  483. X
  484. X@example
  485. Xawk -F- -f baud.awk BBS-list
  486. X@end example
  487. X
  488. X@noindent
  489. XIt produces this output:
  490. X
  491. X@example
  492. Xaardvark     555
  493. Xalpo
  494. Xbarfly       555
  495. Xbites        555
  496. Xcamelot      555
  497. Xcore         555
  498. Xfooey        555
  499. Xfoot         555
  500. Xmacfoo       555
  501. Xsdace        555
  502. Xsabafoo      555
  503. X@end example
  504. X
  505. X@noindent
  506. XNote the second line of output.  If you check the original file, you will
  507. Xsee that the second line looked like this:
  508. X
  509. X@example
  510. Xalpo-net     555-3412     2400/1200/300     A
  511. X@end example
  512. X
  513. XThe @samp{-} as part of the system's name was used as the field
  514. Xseparator, instead of the @samp{-} in the phone number that was
  515. Xoriginally intended.  This demonstrates why you have to be careful in
  516. Xchoosing your field and record separators.
  517. X
  518. XThe following program searches the system password file, and prints
  519. Xthe entries for users who have no password:
  520. X
  521. X@example
  522. Xawk -F: '$2 == ""' /etc/passwd
  523. X@end example
  524. X
  525. X@noindent
  526. XHere we use the @samp{-F} option on the command line to set the field
  527. Xseparator.  Note that fields in @file{/etc/passwd} are separated by
  528. Xcolons.  The second field represents a user's encrypted password, but if
  529. Xthe field is empty, that user has no password.
  530. X
  531. X@node Multiple Line, Getline, Field Separators, Reading Files
  532. X@section Multiple-Line Records
  533. X
  534. X@cindex multiple line records
  535. X@cindex input, multiple line records
  536. X@cindex reading files, multiple line records
  537. X@cindex records, multiple line
  538. XIn some data bases, a single line cannot conveniently hold all the
  539. Xinformation in one entry.  In such cases, you can use multi-line
  540. Xrecords.
  541. X
  542. XThe first step in doing this is to choose your data format: when records
  543. Xare not defined as single lines, how do you want to define them?
  544. XWhat should separate records?
  545. X
  546. XOne technique is to use an unusual character or string to separate
  547. Xrecords.  For example, you could use the formfeed character (written
  548. X@samp{\f} in @code{awk}, as in C) to separate them, making each record
  549. Xa page of the file.  To do this, just set the variable @code{RS} to
  550. X@code{"\f"} (a string containing the formfeed character).  Any
  551. Xother character could equally well be used, as long as it won't be part
  552. Xof the data in a record.
  553. X
  554. X@ignore
  555. XAnother technique is to have blank lines separate records.  The string
  556. X@code{"^\n+"} is a regular expression that matches any sequence of
  557. Xnewlines starting at the beginning of a line---in other words, it
  558. Xmatches a sequence of blank lines.  If you set @code{RS} to this string,
  559. Xa record always ends at the first blank line encountered.  In
  560. Xaddition, a regular expression always matches the longest possible
  561. Xsequence when there is a choice.  So the next record doesn't start until
  562. Xthe first nonblank line that follows---no matter how many blank lines
  563. Xappear in a row, they are considered one record-separator.
  564. X@end ignore
  565. X
  566. XAnother technique is to have blank lines separate records.  By a special
  567. Xdispensation, a null string as the value of @code{RS} indicates that
  568. Xrecords are separated by one or more blank lines.  If you set @code{RS}
  569. Xto the null string, a record always ends at the first blank line
  570. Xencountered.  And the next record doesn't start until the first nonblank
  571. Xline that follows---no matter how many blank lines appear in a row, they
  572. Xare considered one record-separator.
  573. X
  574. XThe second step is to separate the fields in the record.  One way to do
  575. Xthis is to put each field on a separate line: to do this, just set the
  576. Xvariable @code{FS} to the string @code{"\n"}.  (This simple regular
  577. Xexpression matches a single newline.)
  578. X
  579. XAnother idea is to divide each of the lines into fields in the normal
  580. Xmanner.  This happens by default as a result of a special feature: when
  581. X@code{RS} is set to the null string, the newline character @emph{always}
  582. Xacts as a field separator.  This is in addition to whatever field
  583. Xseparations result from @code{FS}.
  584. X
  585. XThe original motivation for this special exception was probably so that
  586. Xyou get useful behavior in the default case (i.e., @w{@code{FS == "
  587. X"}}).  This feature can be a problem if you really don't want the
  588. Xnewline character to separate fields, since there is no way to
  589. Xprevent it.  However, you can work around this by using the @code{split}
  590. Xfunction to break up the record manually (@pxref{String Functions}).
  591. X
  592. X@ignore
  593. XHere are two ways to use records separated by blank lines and break each
  594. Xline into fields normally:
  595. X
  596. X@example
  597. Xawk 'BEGIN @{ RS = ""; FS = "[ \t\n]+" @} @{ print $1 @}' BBS-list
  598. X
  599. X@exdent @r{or}
  600. X
  601. Xawk 'BEGIN @{ RS = "^\n+"; FS = "[ \t\n]+" @} @{ print $1 @}' BBS-list
  602. X@end example
  603. X@end ignore
  604. X
  605. X@ignore
  606. XHere is how to use records separated by blank lines and break each
  607. Xline into fields normally:
  608. X
  609. X@example
  610. Xawk 'BEGIN @{ RS = ""; FS = "[ \t\n]+" @} ; @{ print $1 @}' BBS-list
  611. X@end example
  612. X@end ignore
  613. X
  614. X@node Getline, Close Input, Multiple Line, Reading Files
  615. X@section Explicit Input with @code{getline}
  616. X
  617. X@findex getline
  618. X@cindex input, explicit
  619. X@cindex explicit input
  620. X@cindex input, @code{getline} command
  621. X@cindex reading files, @code{getline} command
  622. XSo far we have been getting our input files from @code{awk}'s main
  623. Xinput stream---either the standard input (usually your terminal) or the
  624. Xfiles specified on the command line.  The @code{awk} language has a
  625. Xspecial built-in command called @code{getline} that
  626. Xcan be used to read input under your explicit control.
  627. X
  628. XThis command is quite complex and should @emph{not} be used by
  629. Xbeginners.  It is covered here because this is the chapter on input.
  630. XThe examples that follow the explanation of the @code{getline} command
  631. Xinclude material that has not been covered yet.  Therefore, come back
  632. Xand study the @code{getline} command @emph{after} you have reviewed the
  633. Xrest of this manual and have a good knowledge of how @code{awk} works.
  634. X
  635. X@code{getline} returns 1 if it finds a record, and 0 if the end of the
  636. Xfile is encountered.  If there is some error in getting a record, such
  637. Xas a file that cannot be opened, then @code{getline} returns @minus{}1.
  638. X
  639. XIn the following examples, @var{command} stands for a string value that
  640. Xrepresents a shell command.
  641. X
  642. X@table @code
  643. X@item getline
  644. XThe @code{getline} command can be used without arguments to read input
  645. Xfrom the current input file.  All it does in this case is read the next
  646. Xinput record and split it up into fields.  This is useful if you've
  647. Xfinished processing the current record, but you want to do some special
  648. Xprocessing @emph{right now} on the next record.  Here's an
  649. Xexample:@refill
  650. X
  651. X@example
  652. Xawk '@{
  653. X     if (t = index($0, "/*")) @{
  654. X          if(t > 1)
  655. X               tmp = substr($0, 1, t - 1)
  656. X          else
  657. X               tmp = ""
  658. X          u = index(substr($0, t + 2), "*/")
  659. X          while (! u) @{
  660. X               getline
  661. X               t = -1
  662. X               u = index($0, "*/")
  663. X          @}
  664. X          if(u <= length($0) - 2)
  665. X               $0 = tmp substr($0, t + u + 3)
  666. X          else
  667. X               $0 = tmp
  668. X     @}
  669. X     print $0
  670. X@}'
  671. X@end example
  672. X
  673. XThis @code{awk} program deletes all comments, @samp{/* @dots{}
  674. X*/}, from the input.  By replacing the @samp{print $0} with other
  675. Xstatements, you could perform more complicated processing on the
  676. Xdecommented input, such as searching it for matches for a regular
  677. Xexpression.
  678. X
  679. XThis form of the @code{getline} command sets @code{NF} (the number of
  680. Xfields; @pxref{Fields}), @code{NR} (the number of records read so far;
  681. X@pxref{Records}), @code{FNR} (the number of records read from this input
  682. Xfile), and the value of @code{$0}.
  683. X
  684. X@strong{Note:} the new value of @code{$0} is used in testing
  685. Xthe patterns of any subsequent rules.  The original value
  686. Xof @code{$0} that triggered the rule which executed @code{getline}
  687. Xis lost.  By contrast, the @code{next} statement reads a new record
  688. Xbut immediately begins processing it normally, starting with the first
  689. Xrule in the program.  @xref{Next Statement}.
  690. X
  691. X@item getline @var{var}
  692. XThis form of @code{getline} reads a record into the variable @var{var}.
  693. XThis is useful when you want your program to read the next record from
  694. Xthe current input file, but you don't want to subject the record to the
  695. Xnormal input processing.
  696. X
  697. XFor example, suppose the next line is a comment, or a special string,
  698. Xand you want to read it, but you must make certain that it won't trigger
  699. Xany rules.  This version of @code{getline} allows you to read that line
  700. Xand store it in a variable so that the main
  701. Xread-a-line-and-check-each-rule loop of @code{awk} never sees it.
  702. X
  703. XThe following example swaps every two lines of input.  For example, given:
  704. X
  705. X@example
  706. Xwan
  707. Xtew
  708. Xfree
  709. Xphore
  710. X@end example
  711. X
  712. X@noindent
  713. Xit outputs:
  714. X
  715. X@example
  716. Xtew
  717. Xwan
  718. Xphore
  719. Xfree
  720. X@end example
  721. X
  722. X@noindent
  723. XHere's the program:
  724. X
  725. X@example
  726. Xawk '@{
  727. X     if ((getline tmp) > 0) @{
  728. X          print tmp
  729. X          print $0
  730. X     @} else
  731. X          print $0
  732. X@}'
  733. X@end example
  734. X
  735. XThe @code{getline} function used in this way sets only the variables
  736. X@code{NR} and @code{FNR} (and of course, @var{var}).  The record is not
  737. Xsplit into fields, so the values of the fields (including @code{$0}) and
  738. Xthe value of @code{NF} do not change.@refill
  739. X
  740. X@item getline < @var{file}
  741. X@cindex input redirection
  742. X@cindex redirection of input
  743. XThis form of the @code{getline} function takes its input from the file
  744. X@var{file}.  Here @var{file} is a string-valued expression that
  745. Xspecifies the file name.  @samp{< @var{file}} is called a @dfn{redirection}
  746. Xsince it directs input to come from a different place.
  747. X
  748. XThis form is useful if you want to read your input from a particular
  749. Xfile, instead of from the main input stream.  For example, the following
  750. Xprogram reads its input record from the file @file{foo.input} when it
  751. Xencounters a first field with a value equal to 10 in the current input
  752. Xfile.@refill
  753. X
  754. X@example
  755. Xawk '@{
  756. Xif ($1 == 10) @{
  757. X     getline < "foo.input"
  758. X     print
  759. X@} else
  760. X     print
  761. X@}'
  762. X@end example
  763. X
  764. XSince the main input stream is not used, the values of @code{NR} and
  765. X@code{FNR} are not changed.  But the record read is split into fields in
  766. Xthe normal manner, so the values of @code{$0} and other fields are
  767. Xchanged.  So is the value of @code{NF}.
  768. X
  769. XThis does not cause the record to be tested against all the patterns
  770. Xin the @code{awk} program, in the way that would happen if the record
  771. Xwere read normally by the main processing loop of @code{awk}.  However
  772. Xthe new record is tested against any subsequent rules, just as when
  773. X@code{getline} is used without a redirection.
  774. X
  775. X@item getline @var{var} < @var{file}
  776. XThis form of the @code{getline} function takes its input from the file
  777. X@var{file} and puts it in the variable @var{var}.  As above, @var{file}
  778. Xis a string-valued expression that specifies the file to read from.
  779. X
  780. XIn this version of @code{getline}, none of the built-in variables are
  781. Xchanged, and the record is not split into fields.  The only variable
  782. Xchanged is @var{var}.
  783. X
  784. XFor example, the following program copies all the input files to the
  785. Xoutput, except for records that say @w{@samp{@@include @var{filename}}}.
  786. XSuch a record is replaced by the contents of the file
  787. X@var{filename}.@refill
  788. X
  789. X@example
  790. Xawk '@{
  791. X     if (NF == 2 && $1 == "@@include") @{
  792. X          while ((getline line < $2) > 0)
  793. X               print line
  794. X          close($2)
  795. X     @} else
  796. X          print
  797. X@}'
  798. X@end example
  799. X
  800. XNote here how the name of the extra input file is not built into
  801. Xthe program; it is taken from the data, from the second field on
  802. Xthe @samp{@@include} line.
  803. X
  804. XThe @code{close} function is called to ensure that if two identical
  805. X@samp{@@include} lines appear in the input, the entire specified file is
  806. Xincluded twice.  @xref{Close Input}.
  807. X
  808. XOne deficiency of this program is that it does not process nested
  809. X@samp{@@include} statements the way a true macro preprocessor would.
  810. X
  811. X@item @var{command} | getline
  812. XYou can @dfn{pipe} the output of a command into @code{getline}.  A pipe is
  813. Xsimply a way to link the output of one program to the input of another.  In
  814. Xthis case, the string @var{command} is run as a shell command and its output
  815. Xis piped into @code{awk} to be used as input.  This form of @code{getline}
  816. Xreads one record from the pipe.
  817. X
  818. XFor example, the following program copies input to output, except for lines
  819. Xthat begin with @samp{@@execute}, which are replaced by the output produced by
  820. Xrunning the rest of the line as a shell command:
  821. X
  822. X@example
  823. Xawk '@{
  824. X     if ($1 == "@@execute") @{
  825. X          tmp = substr($0, 10)
  826. X          while ((tmp | getline) > 0)
  827. X               print
  828. X          close(tmp)
  829. X     @} else
  830. X          print
  831. X@}'
  832. X@end example
  833. X
  834. X@noindent
  835. XThe @code{close} function is called to ensure that if two identical
  836. X@samp{@@execute} lines appear in the input, the command is run again for
  837. Xeach one.  @xref{Close Input}.
  838. X
  839. XGiven the input:
  840. X
  841. X@example
  842. Xfoo
  843. Xbar
  844. Xbaz
  845. X@@execute who
  846. Xbletch
  847. X@end example
  848. X
  849. X@noindent
  850. Xthe program might produce:
  851. X
  852. X@example
  853. Xfoo
  854. Xbar
  855. Xbaz
  856. Xhack     ttyv0   Jul 13 14:22
  857. Xhack     ttyp0   Jul 13 14:23     (gnu:0)
  858. Xhack     ttyp1   Jul 13 14:23     (gnu:0)
  859. Xhack     ttyp2   Jul 13 14:23     (gnu:0)
  860. Xhack     ttyp3   Jul 13 14:23     (gnu:0)
  861. Xbletch
  862. X@end example
  863. X
  864. X@noindent
  865. XNotice that this program ran the command @code{who} and printed the result.
  866. X(If you try this program yourself, you will get different results, showing
  867. Xyou logged in.)
  868. X
  869. XThis variation of @code{getline} splits the record into fields, sets the
  870. Xvalue of @code{NF} and recomputes the value of @code{$0}.  The values of
  871. X@code{NR} and @code{FNR} are not changed.
  872. X
  873. X@item @var{command} | getline @var{var}
  874. XThe output of the command @var{command} is sent through a pipe to
  875. X@code{getline} and into the variable @var{var}.  For example, the
  876. Xfollowing program reads the current date and time into the variable
  877. X@code{current_time}, using the utility called @code{date}, and then
  878. Xprints it.@refill
  879. X
  880. X@group
  881. X@example
  882. Xawk 'BEGIN @{
  883. X     "date" | getline current_time
  884. X     close("date")
  885. X     print "Report printed on " current_time
  886. X@}'
  887. X@end example
  888. X@end group
  889. X
  890. XIn this version of @code{getline}, none of the built-in variables are
  891. Xchanged, and the record is not split into fields.
  892. X@end table
  893. X
  894. X@node Close Input,, Getline, Reading Files
  895. X@section Closing Input Files and Pipes
  896. X@cindex closing input files and pipes
  897. X@findex close
  898. X
  899. XIf the same file name or the same shell command is used with
  900. X@code{getline} more than once during the execution of an @code{awk}
  901. Xprogram, the file is opened (or the command is executed) only the first time.
  902. XAt that time, the first record of input is read from that file or command.
  903. XThe next time the same file or command is used in @code{getline}, another
  904. Xrecord is read from it, and so on.
  905. X
  906. XThis implies that if you want to start reading the same file again from
  907. Xthe beginning, or if you want to rerun a shell command (rather that
  908. Xreading more output from the command), you must take special steps.
  909. XWhat you can do is use the @code{close} function, as follows:
  910. X
  911. X@example
  912. Xclose(@var{filename})
  913. X@end example
  914. X
  915. X@noindent
  916. Xor
  917. X
  918. X@example
  919. Xclose(@var{command})
  920. X@end example
  921. X
  922. XThe argument @var{filename} or @var{command} can be any expression.  Its
  923. Xvalue must exactly equal the string that was used to open the file or
  924. Xstart the command---for example, if you open a pipe with this:
  925. X
  926. X@example
  927. X"sort -r names" | getline foo
  928. X@end example
  929. X
  930. X@noindent
  931. Xthen you must close it with this:
  932. X
  933. X@example
  934. Xclose("sort -r names")
  935. X@end example
  936. X
  937. XOnce this function call is executed, the next @code{getline} from that
  938. Xfile or command will reopen the file or rerun the command.
  939. X
  940. X@node Printing, One-liners, Reading Files, Top
  941. X@chapter Printing Output
  942. X
  943. X@cindex printing
  944. X@cindex output
  945. XOne of the most common things that actions do is to output or @dfn{print}
  946. Xsome or all of the input.  For simple output, use the @code{print}
  947. Xstatement.  For fancier formatting use the @code{printf} statement.
  948. XBoth are described in this chapter.
  949. X
  950. X@menu
  951. X* Print::              The @code{print} statement.
  952. X* Print Examples::     Simple examples of @code{print} statements.
  953. X* Output Separators::  The output separators and how to change them.
  954. X* Printf::             The @code{printf} statement.
  955. X* Redirection::        How to redirect output to multiple files and pipes.
  956. X* Special Files::      File name interpretation in @code{gawk}.  @code{gawk}
  957. X                       allows access to inherited file descriptors.
  958. X@end menu
  959. X
  960. X@node Print, Print Examples, Printing, Printing
  961. X@section The @code{print} Statement
  962. X@cindex @code{print} statement
  963. X
  964. XThe @code{print} statement does output with simple, standardized
  965. Xformatting.  You specify only the strings or numbers to be printed, in a
  966. Xlist separated by commas.  They are output, separated by single spaces,
  967. Xfollowed by a newline.  The statement looks like this:
  968. X
  969. X@example
  970. Xprint @var{item1}, @var{item2}, @dots{}
  971. X@end example
  972. X
  973. X@noindent
  974. XThe entire list of items may optionally be enclosed in parentheses.  The
  975. Xparentheses are necessary if any of the item expressions uses a
  976. Xrelational operator; otherwise it could be confused with a redirection
  977. X(@pxref{Redirection}).  The relational operators are @samp{==},
  978. X@samp{!=}, @samp{<}, @samp{>}, @samp{>=}, @samp{<=}, @samp{~} and
  979. X@samp{!~} (@pxref{Comparison Ops}).@refill
  980. X
  981. XThe items printed can be constant strings or numbers, fields of the
  982. Xcurrent record (such as @code{$1}), variables, or any @code{awk}
  983. Xexpressions.  The @code{print} statement is completely general for
  984. Xcomputing @emph{what} values to print.  With one exception
  985. X(@pxref{Output Separators}), what you can't do is specify @emph{how} to
  986. Xprint them---how many columns to use, whether to use exponential
  987. Xnotation or not, and so on.  For that, you need the @code{printf}
  988. Xstatement (@pxref{Printf}).
  989. X
  990. XThe simple statement @samp{print} with no items is equivalent to
  991. X@samp{print $0}: it prints the entire current record.  To print a blank
  992. Xline, use @samp{print ""}, where @code{""} is the null, or empty,
  993. Xstring.
  994. X
  995. XTo print a fixed piece of text, use a string constant such as
  996. X@w{@code{"Hello there"}} as one item.  If you forget to use the
  997. Xdouble-quote characters, your text will be taken as an @code{awk}
  998. Xexpression, and you will probably get an error.  Keep in mind that a
  999. Xspace is printed between any two items.
  1000. X
  1001. XMost often, each @code{print} statement makes one line of output.  But it
  1002. Xisn't limited to one line.  If an item value is a string that contains a
  1003. Xnewline, the newline is output along with the rest of the string.  A
  1004. Xsingle @code{print} can make any number of lines this way.
  1005. X
  1006. X@node Print Examples, Output Separators, Print, Printing
  1007. X@section Examples of @code{print} Statements
  1008. X
  1009. XHere is an example of printing a string that contains embedded newlines:
  1010. X
  1011. X@example
  1012. Xawk 'BEGIN @{ print "line one\nline two\nline three" @}'
  1013. X@end example
  1014. X
  1015. X@noindent
  1016. Xproduces output like this:
  1017. X
  1018. X@example
  1019. Xline one
  1020. Xline two
  1021. Xline three
  1022. X@end example
  1023. X
  1024. XHere is an example that prints the first two fields of each input record,
  1025. Xwith a space between them:
  1026. X
  1027. X@example
  1028. Xawk '@{ print $1, $2 @}' inventory-shipped
  1029. X@end example
  1030. X
  1031. X@noindent
  1032. XIts output looks like this:
  1033. X
  1034. X@example
  1035. XJan 13
  1036. XFeb 15
  1037. XMar 15
  1038. X@dots{}
  1039. X@end example
  1040. X
  1041. XA common mistake in using the @code{print} statement is to omit the comma
  1042. Xbetween two items.  This often has the effect of making the items run
  1043. Xtogether in the output, with no space.  The reason for this is that
  1044. Xjuxtaposing two string expressions in @code{awk} means to concatenate
  1045. Xthem.  For example, without the comma:
  1046. X
  1047. X@example
  1048. Xawk '@{ print $1 $2 @}' inventory-shipped
  1049. X@end example
  1050. X
  1051. X@noindent
  1052. Xprints:
  1053. X
  1054. X@example
  1055. XJan13
  1056. XFeb15
  1057. XMar15
  1058. X@dots{}
  1059. X@end example
  1060. X
  1061. XNeither example's output makes much sense to someone unfamiliar with the
  1062. Xfile @file{inventory-shipped}.  A heading line at the beginning would make
  1063. Xit clearer.  Let's add some headings to our table of months (@code{$1}) and
  1064. Xgreen crates shipped (@code{$2}).  We do this using the @code{BEGIN} pattern
  1065. X(@pxref{BEGIN/END}) to cause the headings to be printed only once:
  1066. X
  1067. X@c the formatting is strange here because the @{ becomes just a brace.
  1068. X@example
  1069. Xawk 'BEGIN @{  print "Month Crates"
  1070. X              print "----- ------" @}
  1071. X           @{  print $1, $2 @}' inventory-shipped
  1072. X@end example
  1073. X
  1074. X@noindent
  1075. XDid you already guess what happens?  This program prints the following:
  1076. X
  1077. X@group
  1078. X@example
  1079. XMonth Crates
  1080. X----- ------
  1081. XJan 13
  1082. XFeb 15
  1083. XMar 15
  1084. X@dots{}
  1085. X@end example
  1086. X@end group
  1087. X
  1088. X@noindent
  1089. XThe headings and the table data don't line up!  We can fix this by printing
  1090. Xsome spaces between the two fields:
  1091. X
  1092. X@example
  1093. Xawk 'BEGIN @{ print "Month Crates"
  1094. X             print "----- ------" @}
  1095. X           @{ print $1, "     ", $2 @}' inventory-shipped
  1096. X@end example
  1097. X
  1098. XYou can imagine that this way of lining up columns can get pretty
  1099. Xcomplicated when you have many columns to fix.  Counting spaces for two
  1100. Xor three columns can be simple, but more than this and you can get
  1101. X``lost'' quite easily.  This is why the @code{printf} statement was
  1102. Xcreated (@pxref{Printf}); one of its specialties is lining up columns of
  1103. Xdata.
  1104. X
  1105. X@node Output Separators, Printf, Print Examples, Printing
  1106. X@section Output Separators
  1107. X
  1108. X@cindex output field separator, @code{OFS}
  1109. X@vindex OFS
  1110. X@vindex ORS
  1111. X@cindex output record separator, @code{ORS}
  1112. XAs mentioned previously, a @code{print} statement contains a list
  1113. Xof items, separated by commas.  In the output, the items are normally
  1114. Xseparated by single spaces.  But they do not have to be spaces; a
  1115. Xsingle space is only the default.  You can specify any string of
  1116. Xcharacters to use as the @dfn{output field separator} by setting the
  1117. Xbuilt-in variable @code{OFS}.  The initial value of this variable
  1118. Xis the string @w{@code{" "}}.
  1119. X
  1120. XThe output from an entire @code{print} statement is called an
  1121. X@dfn{output record}.  Each @code{print} statement outputs one output
  1122. Xrecord and then outputs a string called the @dfn{output record separator}.
  1123. XThe built-in variable @code{ORS} specifies this string.  The initial
  1124. Xvalue of the variable is the string @code{"\n"} containing a newline
  1125. Xcharacter; thus, normally each @code{print} statement makes a separate line.
  1126. X
  1127. XYou can change how output fields and records are separated by assigning
  1128. Xnew values to the variables @code{OFS} and/or @code{ORS}.  The usual
  1129. Xplace to do this is in the @code{BEGIN} rule (@pxref{BEGIN/END}), so
  1130. Xthat it happens before any input is processed.  You may also do this
  1131. Xwith assignments on the command line, before the names of your input
  1132. Xfiles.
  1133. X
  1134. XThe following example prints the first and second fields of each input
  1135. Xrecord separated by a semicolon, with a blank line added after each
  1136. Xline:@refill
  1137. X
  1138. X@example
  1139. Xawk 'BEGIN @{ OFS = ";"; ORS = "\n\n" @}
  1140. X           @{ print $1, $2 @}'  BBS-list
  1141. X@end example
  1142. X
  1143. XIf the value of @code{ORS} does not contain a newline, all your output
  1144. Xwill be run together on a single line, unless you output newlines some
  1145. Xother way.
  1146. X
  1147. X@node Printf, Redirection, Output Separators, Printing
  1148. X@section Using @code{printf} Statements For Fancier Printing
  1149. X@cindex formatted output
  1150. X@cindex output, formatted
  1151. X
  1152. XIf you want more precise control over the output format than
  1153. X@code{print} gives you, use @code{printf}.  With @code{printf} you can
  1154. Xspecify the width to use for each item, and you can specify various
  1155. Xstylistic choices for numbers (such as what radix to use, whether to
  1156. Xprint an exponent, whether to print a sign, and how many digits to print
  1157. Xafter the decimal point).  You do this by specifying a string, called
  1158. Xthe @dfn{format string}, which controls how and where to print the other
  1159. Xarguments.
  1160. X
  1161. X@menu
  1162. X* Basic Printf::       Syntax of the @code{printf} statement.
  1163. X* Control Letters::    Format-control letters.
  1164. X* Format Modifiers::   Format-specification modifiers.
  1165. X* Printf Examples::    Several examples.
  1166. X@end menu
  1167. X
  1168. X@node Basic Printf, Control Letters, Printf, Printf
  1169. X@subsection Introduction to the @code{printf} Statement
  1170. X
  1171. X@cindex @code{printf} statement, syntax of
  1172. XThe @code{printf} statement looks like this:@refill
  1173. X
  1174. X@example
  1175. Xprintf @var{format}, @var{item1}, @var{item2}, @dots{}
  1176. X@end example
  1177. X
  1178. X@noindent
  1179. XThe entire list of items may optionally be enclosed in parentheses.  The
  1180. Xparentheses are necessary if any of the item expressions uses a
  1181. Xrelational operator; otherwise it could be confused with a redirection
  1182. X(@pxref{Redirection}).  The relational operators are @samp{==},
  1183. X@samp{!=}, @samp{<}, @samp{>}, @samp{>=}, @samp{<=}, @samp{~} and
  1184. X@samp{!~} (@pxref{Comparison Ops}).@refill
  1185. X
  1186. X@cindex format string
  1187. XThe difference between @code{printf} and @code{print} is the argument
  1188. X@var{format}.  This is an expression whose value is taken as a string; its
  1189. Xjob is to say how to output each of the other arguments.  It is called
  1190. Xthe @dfn{format string}.
  1191. X
  1192. XThe format string is essentially the same as in the C library function
  1193. X@code{printf}.  Most of @var{format} is text to be output verbatim.
  1194. XScattered among this text are @dfn{format specifiers}, one per item.
  1195. XEach format specifier says to output the next item at that place in the
  1196. Xformat.@refill
  1197. X
  1198. XThe @code{printf} statement does not automatically append a newline to its
  1199. Xoutput.  It outputs nothing but what the format specifies.  So if you want
  1200. Xa newline, you must include one in the format.  The output separator
  1201. Xvariables @code{OFS} and @code{ORS} have no effect on @code{printf}
  1202. Xstatements.
  1203. X
  1204. X@node Control Letters, Format Modifiers, Basic Printf, Printf
  1205. X@subsection Format-Control Letters
  1206. X@cindex @code{printf}, format-control characters
  1207. X@cindex format specifier
  1208. X
  1209. XA format specifier starts with the character @samp{%} and ends with a
  1210. X@dfn{format-control letter}; it tells the @code{printf} statement how
  1211. Xto output one item.  (If you actually want to output a @samp{%}, write
  1212. X@samp{%%}.)  The format-control letter specifies what kind of value to
  1213. Xprint.  The rest of the format specifier is made up of optional
  1214. X@dfn{modifiers} which are parameters such as the field width to use.
  1215. X
  1216. XHere is a list of the format-control letters:
  1217. X
  1218. X@table @samp
  1219. X@item c
  1220. XThis prints a number as an ASCII character.  Thus, @samp{printf "%c",
  1221. X65} outputs the letter @samp{A}.  The output for a string value is
  1222. Xthe first character of the string.
  1223. X
  1224. X@item d
  1225. XThis prints a decimal integer.
  1226. X
  1227. X@item i
  1228. XThis also prints a decimal integer.
  1229. X
  1230. X@item e
  1231. XThis prints a number in scientific (exponential) notation.
  1232. XFor example,
  1233. X
  1234. X@example
  1235. Xprintf "%4.3e", 1950
  1236. X@end example
  1237. X
  1238. X@noindent
  1239. Xprints @samp{1.950e+03}, with a total of 4 significant figures of
  1240. Xwhich 3 follow the decimal point.  The @samp{4.3} are @dfn{modifiers},
  1241. Xdiscussed below.
  1242. X
  1243. X@item f
  1244. XThis prints a number in floating point notation.
  1245. X
  1246. X@item g
  1247. XThis prints either scientific notation or floating point notation, whichever
  1248. Xis shorter.
  1249. X
  1250. X@item o
  1251. XThis prints an unsigned octal integer.
  1252. X
  1253. X@item s
  1254. XThis prints a string.
  1255. X
  1256. X@item x
  1257. XThis prints an unsigned hexadecimal integer.
  1258. X
  1259. X@item X
  1260. XThis prints an unsigned hexadecimal integer.  However, for the values 10
  1261. Xthrough 15, it uses the letters @samp{A} through @samp{F} instead of
  1262. X@samp{a} through @samp{f}.
  1263. X
  1264. X@item %
  1265. XThis isn't really a format-control letter, but it does have a meaning
  1266. Xwhen used after a @samp{%}: the sequence @samp{%%} outputs one
  1267. X@samp{%}.  It does not consume an argument.
  1268. X@end table
  1269. X
  1270. X@node Format Modifiers, Printf Examples, Control Letters, Printf
  1271. X@subsection Modifiers for @code{printf} Formats
  1272. X
  1273. X@cindex @code{printf}, modifiers
  1274. X@cindex modifiers (in format specifiers)
  1275. XA format specification can also include @dfn{modifiers} that can control
  1276. Xhow much of the item's value is printed and how much space it gets.  The
  1277. Xmodifiers come between the @samp{%} and the format-control letter.  Here
  1278. Xare the possible modifiers, in the order in which they may appear:
  1279. X
  1280. X@table @samp
  1281. X@item -
  1282. XThe minus sign, used before the width modifier, says to left-justify
  1283. Xthe argument within its specified width.  Normally the argument
  1284. Xis printed right-justified in the specified width.  Thus,
  1285. X
  1286. X@example
  1287. Xprintf "%-4s", "foo"
  1288. X@end example
  1289. X
  1290. X@noindent
  1291. Xprints @samp{foo }.
  1292. X
  1293. X@item @var{width}
  1294. XThis is a number representing the desired width of a field.  Inserting any
  1295. Xnumber between the @samp{%} sign and the format control character forces the
  1296. Xfield to be expanded to this width.  The default way to do this is to
  1297. Xpad with spaces on the left.  For example,
  1298. X
  1299. X@example
  1300. Xprintf "%4s", "foo"
  1301. X@end example
  1302. X
  1303. X@noindent
  1304. Xprints @samp{ foo}.
  1305. X
  1306. XThe value of @var{width} is a minimum width, not a maximum.  If the item
  1307. Xvalue requires more than @var{width} characters, it can be as wide as
  1308. Xnecessary.  Thus,
  1309. X
  1310. X@example
  1311. Xprintf "%4s", "foobar"
  1312. X@end example
  1313. X
  1314. X@noindent
  1315. Xprints @samp{foobar}.  Preceding the @var{width} with a minus sign causes
  1316. Xthe output to be padded with spaces on the right, instead of on the left.
  1317. X
  1318. X@item .@var{prec}
  1319. XThis is a number that specifies the precision to use when printing.
  1320. XThis specifies the number of digits you want printed to the right of the
  1321. Xdecimal point.  For a string, it specifies the maximum number of
  1322. Xcharacters from the string that should be printed.
  1323. X@end table
  1324. X
  1325. XThe C library @code{printf}'s dynamic @var{width} and @var{prec}
  1326. Xcapability (for example, @code{"%*.*s"}) is not yet supported.  However, it can
  1327. Xeasily be simulated using concatenation to dynamically build the
  1328. Xformat string.@refill
  1329. X
  1330. X@node Printf Examples, , Format Modifiers, Printf
  1331. X@subsection Examples of Using @code{printf}
  1332. X
  1333. XHere is how to use @code{printf} to make an aligned table:
  1334. X
  1335. X@example
  1336. Xawk '@{ printf "%-10s %s\n", $1, $2 @}' BBS-list
  1337. X@end example
  1338. X
  1339. X@noindent
  1340. Xprints the names of bulletin boards (@code{$1}) of the file
  1341. X@file{BBS-list} as a string of 10 characters, left justified.  It also
  1342. Xprints the phone numbers (@code{$2}) afterward on the line.  This
  1343. Xproduces an aligned two-column table of names and phone numbers:
  1344. X
  1345. X@example
  1346. Xaardvark   555-5553
  1347. Xalpo-net   555-3412
  1348. Xbarfly     555-7685
  1349. Xbites      555-1675
  1350. Xcamelot    555-0542
  1351. Xcore       555-2912
  1352. Xfooey      555-1234
  1353. Xfoot       555-6699
  1354. Xmacfoo     555-6480
  1355. Xsdace      555-3430
  1356. Xsabafoo    555-2127
  1357. X@end example
  1358. X
  1359. XDid you notice that we did not specify that the phone numbers be printed
  1360. Xas numbers?  They had to be printed as strings because the numbers are
  1361. Xseparated by a dash.  This dash would be interpreted as a minus sign if
  1362. Xwe had tried to print the phone numbers as numbers.  This would have led
  1363. Xto some pretty confusing results.
  1364. X
  1365. XWe did not specify a width for the phone numbers because they are the
  1366. Xlast things on their lines.  We don't need to put spaces after them.
  1367. X
  1368. XWe could make our table look even nicer by adding headings to the tops
  1369. Xof the columns.  To do this, use the @code{BEGIN} pattern
  1370. X(@pxref{BEGIN/END}) to cause the header to be printed only once, at the
  1371. Xbeginning of the @code{awk} program:
  1372. X
  1373. X@example
  1374. Xawk 'BEGIN @{ print "Name      Number"
  1375. X             print "----      ------" @}
  1376. X     @{ printf "%-10s %s\n", $1, $2 @}' BBS-list
  1377. X@end example
  1378. X
  1379. XDid you notice that we mixed @code{print} and @code{printf} statements in
  1380. Xthe above example?  We could have used just @code{printf} statements to get
  1381. Xthe same results:
  1382. X
  1383. X@example
  1384. Xawk 'BEGIN @{ printf "%-10s %s\n", "Name", "Number"
  1385. X             printf "%-10s %s\n", "----", "------" @}
  1386. X     @{ printf "%-10s %s\n", $1, $2 @}' BBS-list
  1387. X@end example
  1388. X
  1389. X@noindent
  1390. XBy outputting each column heading with the same format specification
  1391. Xused for the elements of the column, we have made sure that the headings
  1392. Xare aligned just like the columns.
  1393. X
  1394. XThe fact that the same format specification is used three times can be
  1395. Xemphasized by storing it in a variable, like this:
  1396. X
  1397. X@example
  1398. Xawk 'BEGIN @{ format = "%-10s %s\n"
  1399. X             printf format, "Name", "Number"
  1400. END_OF_FILE
  1401.   if test 49665 -ne `wc -c <'./gawk.texinfo.02'`; then
  1402.     echo shar: \"'./gawk.texinfo.02'\" unpacked with wrong size!
  1403.   fi
  1404.   # end of './gawk.texinfo.02'
  1405. fi
  1406. if test -f './regex.c.02' -a "${1}" != "-c" ; then 
  1407.   echo shar: Will not clobber existing file \"'./regex.c.02'\"
  1408. else
  1409.   echo shar: Extracting \"'./regex.c.02'\" \(2044 characters\)
  1410.   sed "s/^X//" >'./regex.c.02' <<'END_OF_FILE'
  1411. X    0360, 0361, 0362, 0363, 0364, 0365, 0366, 0367,
  1412. X    0370, 0371, 0372, 0373, 0374, 0375, 0376, 0377
  1413. X  };
  1414. X
  1415. Xmain (argc, argv)
  1416. X     int argc;
  1417. X     char **argv;
  1418. X{
  1419. X  char pat[80];
  1420. X  struct re_pattern_buffer buf;
  1421. X  int i;
  1422. X  char c;
  1423. X  char fastmap[(1 << BYTEWIDTH)];
  1424. X
  1425. X  /* Allow a command argument to specify the style of syntax.  */
  1426. X  if (argc > 1)
  1427. X    obscure_syntax = atoi (argv[1]);
  1428. X
  1429. X  buf.allocated = 40;
  1430. X  buf.buffer = (char *) malloc (buf.allocated);
  1431. X  buf.fastmap = fastmap;
  1432. X  buf.translate = upcase;
  1433. X
  1434. X  while (1)
  1435. X    {
  1436. X      gets (pat);
  1437. X
  1438. X      if (*pat)
  1439. X    {
  1440. X          re_compile_pattern (pat, strlen(pat), &buf);
  1441. X
  1442. X      for (i = 0; i < buf.used; i++)
  1443. X        printchar (buf.buffer[i]);
  1444. X
  1445. X      putchar ('\n');
  1446. X
  1447. X      printf ("%d allocated, %d used.\n", buf.allocated, buf.used);
  1448. X
  1449. X      re_compile_fastmap (&buf);
  1450. X      printf ("Allowed by fastmap: ");
  1451. X      for (i = 0; i < (1 << BYTEWIDTH); i++)
  1452. X        if (fastmap[i]) printchar (i);
  1453. X      putchar ('\n');
  1454. X    }
  1455. X
  1456. X      gets (pat);    /* Now read the string to match against */
  1457. X
  1458. X      i = re_match (&buf, pat, strlen (pat), 0, 0);
  1459. X      printf ("Match value %d.\n", i);
  1460. X    }
  1461. X}
  1462. X
  1463. X#ifdef NOTDEF
  1464. Xprint_buf (bufp)
  1465. X     struct re_pattern_buffer *bufp;
  1466. X{
  1467. X  int i;
  1468. X
  1469. X  printf ("buf is :\n----------------\n");
  1470. X  for (i = 0; i < bufp->used; i++)
  1471. X    printchar (bufp->buffer[i]);
  1472. X  
  1473. X  printf ("\n%d allocated, %d used.\n", bufp->allocated, bufp->used);
  1474. X  
  1475. X  printf ("Allowed by fastmap: ");
  1476. X  for (i = 0; i < (1 << BYTEWIDTH); i++)
  1477. X    if (bufp->fastmap[i])
  1478. X      printchar (i);
  1479. X  printf ("\nAllowed by translate: ");
  1480. X  if (bufp->translate)
  1481. X    for (i = 0; i < (1 << BYTEWIDTH); i++)
  1482. X      if (bufp->translate[i])
  1483. X    printchar (i);
  1484. X  printf ("\nfastmap is%s accurate\n", bufp->fastmap_accurate ? "" : "n't");
  1485. X  printf ("can %s be null\n----------", bufp->can_be_null ? "" : "not");
  1486. X}
  1487. X#endif
  1488. X
  1489. Xprintchar (c)
  1490. X     char c;
  1491. X{
  1492. X  if (c < 041 || c >= 0177)
  1493. X    {
  1494. X      putchar ('\\');
  1495. X      putchar (((c >> 6) & 3) + '0');
  1496. X      putchar (((c >> 3) & 7) + '0');
  1497. X      putchar ((c & 7) + '0');
  1498. X    }
  1499. X  else
  1500. X    putchar (c);
  1501. X}
  1502. X
  1503. X#endif /* test */
  1504. END_OF_FILE
  1505.   if test 2044 -ne `wc -c <'./regex.c.02'`; then
  1506.     echo shar: \"'./regex.c.02'\" unpacked with wrong size!
  1507.   fi
  1508.   # end of './regex.c.02'
  1509. fi
  1510. echo shar: End of archive 5 \(of 16\).
  1511. cp /dev/null ark5isdone
  1512. MISSING=""
  1513. for I in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ; do
  1514.     if test ! -f ark${I}isdone ; then
  1515.     MISSING="${MISSING} ${I}"
  1516.     fi
  1517. done
  1518. if test "${MISSING}" = "" ; then
  1519.     echo You have unpacked all 16 archives.
  1520.     rm -f ark[1-9]isdone ark[1-9][0-9]isdone
  1521. else
  1522.     echo You still must unpack the following archives:
  1523.     echo "        " ${MISSING}
  1524. fi
  1525. exit 0
  1526. exit 0 # Just in case...
  1527.